package cn.imatu.framework.tool.core;

import cn.hutool.core.util.StrUtil;
import cn.imatu.framework.exception.BizException;
import cn.imatu.framework.tool.core.http.UrlEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;

/**
 * url工具类
 *
 * @author shenguangyang
 */
public class UrlUtils {
    private static final Logger log = LoggerFactory.getLogger(UrlUtils.class);

    /**
     * 移除url起始斜杠
     * 比如
     * 输入 /opt
     * 输出 opt
     *
     * @param url url
     */
    public static String removeStartsSlash(String url) {
        if (StringUtils.isNull(url)) {
            log.warn("removeStartsSlash::url = [{}]", url);
            return "";
        }
        boolean isExistStartsSlash = url.startsWith("/") || url.startsWith("\\");
        if (isExistStartsSlash) {
            return url.substring(1);
        }
        return url;
    }

    /**
     * 添加url起始斜杠
     * 比如
     * 输入 opt
     * 输出 /opt
     *
     * @param url url
     */
    public static String addStartsSlash(String url) {
        if (StringUtils.isNull(url)) {
            log.warn("addStartsSlash::url = [{}]", url);
            return "";
        }
        boolean isExistStartsSlash = url.startsWith("/") || url.startsWith("\\");
        if (!isExistStartsSlash) {
            return "/" + url;
        }
        return url;
    }

    /**
     * 添加url最后的斜杠
     * 比如
     * 输入 <a href="">http://127.0.0.1:9000</a>
     * 输出 <a href="">http://127.0.0.1:9000/</a>
     *
     * @param url url
     */
    public static String addEndSlash(String url) {
        if (StringUtils.isNull(url)) {
            log.warn("removeLastSlash::url = [{}]", url);
            return "";
        }
        boolean isExistLastSlash = url.endsWith("/") || url.endsWith("\\");
        if (!isExistLastSlash) {
            return url + "/";
        }
        return url;
    }

    /**
     * 移除url最后的斜杠
     * 比如
     * 输入 <a href="">http://127.0.0.1:9000/</a>
     * 输出  <a href="">http://127.0.0.1:9000</a>
     *
     * @param url url
     */
    public static String removeEndSlash(String url) {
        if (StringUtils.isNull(url)) {
            log.warn("removeEndSlash::url = [{}]", url);
            return "";
        }
        boolean isExistLastSlash = url.endsWith("/") || url.endsWith("\\");
        if (isExistLastSlash) {
            return url.substring(0, url.length() - 1);
        }
        return url;
    }

    /**
     * 移除url中重复的斜杠
     */
    public static String removeRepeatSlashOfUrl(String srcUrl) {
        if (StringUtils.isEmpty(srcUrl)) {
            return "";
        }
        StringBuilder targetUrl = new StringBuilder();
        if (srcUrl.contains("http://")) {
            srcUrl = srcUrl.replace("http://", "");
            targetUrl.append("http://");
        } else if (srcUrl.contains("https://")) {
            srcUrl = srcUrl.replace("https://", "");
            targetUrl.append("https://");
        }
        boolean isEndWithSlash = srcUrl.endsWith("/");
        boolean isStartWithSlash = srcUrl.startsWith("/");
        String[] split = srcUrl.split("/");
        Arrays.stream(split)
                .filter(StringUtils::isNotEmpty)
                .forEach(item -> targetUrl.append(item).append("/"));
        String respUrl = targetUrl.toString();
        if (!isEndWithSlash) {
            respUrl = respUrl.substring(0, targetUrl.lastIndexOf("/"));
        }
        if (isStartWithSlash) {
            respUrl = "/" + respUrl;
        }
        return respUrl;
    }

    /**
     * 获取url(可以带有参数)
     *
     * @param baseUrl   基本url
     * @param routeUri  路由的url
     * @param urlParams 路径参数
     * @return 完成url
     */
    public static <T> String getUrl(String baseUrl, String routeUri, Map<String, T> urlParams) {
        StringBuilder urlSb = new StringBuilder(removeRepeatSlashOfUrl(baseUrl + "/" + (StringUtils.isEmpty(routeUri) ? "" : routeUri + "/")));
        if (Objects.nonNull(urlParams) && !urlParams.isEmpty()) {
            urlSb.append("?");
            urlParams.forEach((k, v) -> {
               try {
                   if (v == null || StrUtil.isEmpty(v.toString())) {
                       return;
                   }
                   String value = v.toString();
                   String decodeValue = URLDecoder.decode(value, "utf-8");
                   urlSb.append(k).append("=").append(URLEncoder.encode(decodeValue, "utf-8")).append("&");
               } catch (Exception e) {
                   log.error("error: ", e);
                   throw new BizException("生成url异常 {}?{}={}", baseUrl, k, v);
               }
            });
        }
        return StrUtil.replaceLast(urlSb.toString(), "&", "");
    }

    /**
     * 获取url(可以带有参数)
     *
     * @param baseUrl   基本url
     * @param urlParams 路径参数
     * @return 完成url
     */
    public static <T> String getUrl(String baseUrl, Map<String, T> urlParams) {
       return getUrl(baseUrl, null, urlParams);
    }
}
